/*
 * @Author: zjj
 * @Date: 2019-11-04 10:56:57
 * @LastEditors: zjj
 * @LastEditTime: 2019-12-25 11:09:55
 */
const compress = function (file) {
  //将base64转换为文件
  function dataURLtoFile(dataurl) {
    var arr = dataurl.split(","),
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], file.file.name, {
      type: file.file.type
    });
  }
  return new Promise((resolve, reject) => {
    if (parseInt(file.file.size) / 1024 < 900) {
      resolve(file.file)
      return 
    }
    var reader = new FileReader();
    reader.addEventListener(
      "load",
      function () {
        let img = new Image();
        img.src = reader.result;
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");


        img.onload = () => {
          canvas.width = img.width;
          canvas.height = img.height;
          // 铺底色
          ctx.fillStyle = "#fff";
          ctx.fillRect(0, 0, canvas.width, canvas.height);
          ctx.drawImage(img, 0, 0, img.width, img.height);

          //进行最小压缩
          let ndata = canvas.toDataURL(file.file.type, 0.3);
          let newFile=dataURLtoFile(ndata)
          resolve(newFile)
        }

      },
      false
    );

    if (file.file) {
      reader.readAsDataURL(file.file);
    }
  })



}
export default compress